package capstoneproject.dudiachi.Main;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.StringTokenizer;

import org.w3c.dom.Document;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import capstoneproject.dudiachi.Controller.GMapV2Direction;
import capstoneproject.dudiachi.Controller.InternetConnectionDetector;
import capstoneproject.dudiachi.Controller.PlaceManager;
import capstoneproject.dudiachi.Model.Place;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;


public class GoogleMapActivity extends BaseActivity implements
		LocationListener, OnMarkerClickListener, OnClickListener {
	protected LocationManager locationManager;
	// flag for GPS status
	boolean isGPSEnabled = false;

	// flag for network status
	boolean isNetworkEnabled = false;

	Location location; 
	double latitude; 
	double longitude; 
	private GoogleMap map;
	GMapV2Direction myDirection;
	public static Location myLocation;
	private Marker myMarker;
	private ViewGroup hiddenPanel;
	private ArrayList<Place> listPlace;
	private ArrayList<Marker> listMarker;
	private Polyline polylineFinal;
	private PlaceManager manager;
	private ImageView image;
	private TextView des;
	private TextView name;
	
	// The minimum distance to change Updates in meters
	private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

	// The minimum time between updates in milliseconds
	private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
	public static Context CONTEXT = null;

	public static FragmentManager fragmentManager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		BaseActivity.POS = 2;
		setContentView(R.layout.activity_google_map);
		// Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

		//		21.041749,105.763748
		hiddenPanel = (ViewGroup) findViewById(R.id.hidden_panel);
		manager = new PlaceManager(getApplicationContext());
		listPlace = manager.getListPlace();
		name = (TextView) findViewById(R.id.name);
		des = (TextView) findViewById(R.id.des);
		image = (ImageView) findViewById(R.id.image);
		myLocation = getLocation();
		
//		fragmentManager = getSupportFragmentManager();
		if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
		myDirection = new GMapV2Direction();
		map = ((SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map)).getMap();
//		getSupportFragmentManager().beginTransaction()
//				.replace(R.id.displayMap, new GoogleMapFragment()).commit();
		setUpMap();
		
		
	}
	
	private void setUpMap() {
		
		listMarker = new ArrayList<Marker>();
		map.clear();
		map.setMyLocationEnabled(true);
		
			if (myLocation != null) {
				if(isNetworkEnabled){
				for(Place item : listPlace){
					if (item.getPlaceType().equals("AT")) {
						myMarker = map.addMarker(new MarkerOptions()
								.position(
										new LatLng(item.getLatitude(), item
												.getLongitude()))
								.title(item.getPlaceName())
								.snippet(item.getPlaceType())
								.icon(BitmapDescriptorFactory
										.fromResource(R.drawable.anuong)));
						listMarker.add(myMarker);
					}
					if (item.getPlaceType().equals("LN")) {
						myMarker = map.addMarker(new MarkerOptions()
								.position(
										new LatLng(item.getLatitude(), item
												.getLongitude()))
								.title(item.getPlaceName())
								.snippet(item.getPlaceType())
								.icon(BitmapDescriptorFactory
										.fromResource(R.drawable.luuniem)));
						listMarker.add(myMarker);
					}
					if (item.getPlaceType().equals("TQ")) {
						myMarker = map.addMarker(new MarkerOptions()
								.position(
										new LatLng(item.getLatitude(), item
												.getLongitude()))
								.title(item.getPlaceName())
								.snippet(item.getPlaceType())
								.icon(BitmapDescriptorFactory
										.fromResource(R.drawable.thamquan)));
						listMarker.add(myMarker);
					}
				}
			}
			map.setOnMarkerClickListener(this);
			LatLng myLatLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
			CameraPosition myPos = new CameraPosition.Builder().target(myLatLng).zoom(16).build();
			map.animateCamera(CameraUpdateFactory.newCameraPosition(myPos));
			
			Intent intent = getIntent();
			String tag = "";
			
			if(intent!=null){
				tag = intent.getStringExtra("tag");
				if(tag!=null){
					directionFromPlace(intent.getStringExtra("id"));
				}
			}
		} 
		
	}
	
//	@Override
//	public void onDestroy() {
//		super.onDestroy();
//
//		try {
//			getSupportFragmentManager()
//					.beginTransaction()
//					.remove(getSupportFragmentManager()
//							.findFragmentById(R.id.map)).commit();
//		} catch (Exception e) {
//		}
//	}
	
	public Location getLocation() {
		try {
			locationManager = (LocationManager) getApplicationContext()
					.getSystemService(Context.LOCATION_SERVICE);

			isGPSEnabled = locationManager
					.isProviderEnabled(LocationManager.GPS_PROVIDER);

			InternetConnectionDetector icd = new InternetConnectionDetector(getApplicationContext());
			isNetworkEnabled = icd.checkInternetConnection();

			if (!isGPSEnabled || !isNetworkEnabled) {
				// no network provider is enabled
				Toast.makeText(getApplicationContext(),
						"Hãy bật GPS và kết nối mạng!", Toast.LENGTH_LONG)
						.show();
//				Intent i = new Intent(this, HomeActivity.class);
//				startActivity(i);
			}
//			else {
				
				if (isNetworkEnabled) {
					locationManager.requestLocationUpdates(
							LocationManager.NETWORK_PROVIDER,
							MIN_TIME_BW_UPDATES,
							MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
					Log.d("activity", "LOC Network Enabled");
					if (locationManager != null) {
						location = locationManager
								.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
						if (location != null) {
							Log.d("activity", "LOC by Network");
							latitude = location.getLatitude();
							longitude = location.getLongitude();
						}
					}
				}
				// if GPS Enabled get lat/long using GPS Services
				if (isGPSEnabled) {
					if (location == null) {
						locationManager.requestLocationUpdates(
								LocationManager.GPS_PROVIDER,
								MIN_TIME_BW_UPDATES,
								MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
						Log.d("activity", "RLOC: GPS Enabled");
						if (locationManager != null) {
							location = locationManager
									.getLastKnownLocation(LocationManager.GPS_PROVIDER);
							if (location != null) {
								Log.d("activity", "RLOC: loc by GPS");
								latitude = location.getLatitude();
								longitude = location.getLongitude();
							}
						}
					}
				}
//			}
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"Hãy bật GPS và kết nối mạng!", Toast.LENGTH_LONG)
					.show();
			e.printStackTrace();
		}
		return location;
	}


	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}
	
	private boolean isPanelShown() {
        return hiddenPanel.getVisibility() == View.VISIBLE;
    }
	
	@Override
	public boolean onMarkerClick(Marker marker) {
		
		LatLng myPosition = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
		LatLng toLocation = marker.getPosition();
		for (Marker item : listMarker) {
			if (marker.equals(item)) {
				
				for (Place item2 : listPlace) {
					if (item2.getPlaceName().equals(marker.getTitle())) {
//						toLocation = new LatLng(item2.getLatitude(), item2.getLongitude());
						name.setText(item2.getPlaceName());
						des.setText(randomText(item2.getDescription()));
						try {
							image.setImageBitmap(GetBitmapFromAsset.getBitmapFromAsset(this, "Images/DiaDanh/" + item2.getImage1()));
							image.setTag(""+item2.getPlaceID());
							image.setOnClickListener(this);
							hiddenPanel.setTag(""+item2.getPlaceID());
							hiddenPanel.setOnClickListener(this);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}

				if (!isPanelShown()) {
					Animation bottomUp = AnimationUtils.loadAnimation(this,
							R.anim.bottom_up);

					hiddenPanel.startAnimation(bottomUp);
					hiddenPanel.setVisibility(View.VISIBLE);
				}
			}
		}
		if(polylineFinal!=null){
			polylineFinal.remove();
		}
		Document doc = myDirection.getDocument(myPosition, toLocation, GMapV2Direction.MODE_DRIVING);
		ArrayList<LatLng> directionPoint = myDirection.getDirection(doc);
		PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.RED);
		
		for(int i = 0 ; i < directionPoint.size() ; i++) {			
			rectLine.add(directionPoint.get(i));
		}

		polylineFinal = map.addPolyline(rectLine);
		
		return false;
	}
	
	public void slideDown(final View view){
		if(isPanelShown()){
			Animation bottomDown = AnimationUtils.loadAnimation(this,
                    R.anim.bottom_down);

            hiddenPanel.startAnimation(bottomDown);
            hiddenPanel.setVisibility(View.GONE);
		}
	}
	public void directionFromPlace(String id){
			
		Place searchingPlace = manager.searchByID(id);
		LatLng myPosition = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
		LatLng toLocation = new LatLng(searchingPlace.getLatitude(), searchingPlace.getLongitude());
		CameraPosition myPos = new CameraPosition.Builder().target(toLocation).zoom(16).build();
		map.animateCamera(CameraUpdateFactory.newCameraPosition(myPos));
		
		if(polylineFinal!=null){
			polylineFinal.remove();
		}
		Document doc = myDirection.getDocument(myPosition, toLocation, GMapV2Direction.MODE_DRIVING);
		ArrayList<LatLng> directionPoint = myDirection.getDirection(doc);
		PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.RED);
		
		for(int i = 0 ; i < directionPoint.size() ; i++) {			
			rectLine.add(directionPoint.get(i));
		}

		polylineFinal = map.addPolyline(rectLine);
		
		name.setText(searchingPlace.getPlaceName());
		des.setText(randomText(searchingPlace.getDescription()));
		try {
			image.setImageBitmap(GetBitmapFromAsset.getBitmapFromAsset(this, "Images/DiaDanh/" + searchingPlace.getImage1()));
			image.setTag(""+searchingPlace.getPlaceID());
			image.setOnClickListener(this);
			hiddenPanel.setTag(""+searchingPlace.getPlaceID());
			hiddenPanel.setOnClickListener(this);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Animation bottomUp = AnimationUtils.loadAnimation(this,
				R.anim.bottom_up);

		hiddenPanel.startAnimation(bottomUp);
		hiddenPanel.setVisibility(View.VISIBLE);
		
	}
	public String randomText(String str){
		ArrayList<String> strList = new ArrayList<String>();
		StringTokenizer token = new StringTokenizer(str,"|");
		while(token.hasMoreTokens()){
			strList.add(token.nextToken());
		}
		Random random = new Random();
		int choice = random.nextInt(strList.size());
		String pickedString = strList.get(choice);
		return pickedString;
	}
	
	@Override
	public void onClick(View v) {
		String tag = (String) v.getTag();
		Intent intent = new Intent(this, DetailPlaceActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Bundle bundle = new Bundle();
		bundle.putSerializable("list", listPlace);
		bundle.putString("id", tag);
		intent.putExtras(bundle);
		startActivity(intent);
	}
	
	
}